package cn.hp.controller;

import cn.hp.bean.Customer;
import cn.hp.bean.Order;
import cn.hp.service.CustomerService;
import cn.hp.service.OrderService;
import cn.hp.utils.JsonData;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CustomerService customerService;

    @RequestMapping("/selectOrdersList")
    @ResponseBody
    public JsonData selectOrdersList(String phone, String status, Integer page, Integer limit){
        Map<String,Object> map=new HashMap<String, Object>();

        if (!StringUtils.isEmpty(phone)){
            map.put("phone", phone);
        }

        if (!StringUtils.isEmpty(status)){
            map.put("status", status);
        }

        JsonData jsonData = orderService.selectOrdersList(map, page, limit);
        return jsonData;
    }

    @RequestMapping("/addOrder")
    @ResponseBody
    public JsonData addOrder(Order order, String car, String name){
        order.setStatus("0");
        order.setCreatetime(new Date());


        List<Order> list = (List<Order>) orderService.selectListByPhone(order.getPhone()).getData();//根据手机号查询订单列表 判断该手机号是否包含未完成订单
        String s="";
        if(list.size()>0){
            for(Order o:list){
                s+=o.getStatus();
            }
        }
        if(s.contains("0")){//如果字符串包含0 代表该账户已有订单
            return JsonData.buildError("该客户已有订单");
        } else{
            Customer customer=customerService.findCuPhone(order.getPhone());//在顾客列表里查询是否包含该顾客
            if(customer==null){
                int ci=customerService.addCusromer(order.getPhone(),name,car);//进行顾客添加
                JsonData jsonData = orderService.addOrder(order);//进行订单添加
                if (ci>0&&jsonData.getCode()==200){
                    return JsonData.buildSuc("顾客和用户，添加成功");
                }
            }else{
                JsonData jsonData = orderService.addOrder(order);
                return jsonData;
            }

        }
        return JsonData.buildError("服务器偷懒了");
    }

    @RequestMapping("/upd")
    @ResponseBody
    public JsonData upd(String id,String status){
        JsonData jsonData=orderService.updateSta(id,status);
        return jsonData;
    }
}
